"""
将指定资源文件夹中匹配到的文件
解析出相应的html并提取出静态资源
"""
import re
import shutil
from pathlib import Path

from utils import OpenWordFile, get_md5, word_app
from wash_dom import transfer_dom

BASE_DIR = Path(__file__).parent.resolve()

SRC_PATH_LIST = ['./example']
STATIC_FILE_PREFIX = '/media/'

TGT_PATH = BASE_DIR / 'dist'
TGT_HTML_PATH = TGT_PATH / 'html'
TGT_STATIC_PATH = TGT_PATH / 'static'
TEMP_PATH = TGT_PATH / '_temp_'

TGT_HTML_PATH.mkdir(parents=True, exist_ok=True)
TGT_STATIC_PATH.mkdir(parents=True, exist_ok=True)
TEMP_PATH.mkdir(parents=True, exist_ok=True)


def process_file_data(file_data):
    """接收文件名,文件的MD5值,以及文件的HTML内容"""
    with open(str(TGT_HTML_PATH / f"{file_data['file_md5_value']}.html"), 'wt') as f:
        html = transfer_dom(file_data['content'])
        f.write(html)


def parse(word_file: Path):
    """将word文件另保存为html文件,并将"""
    file_md5_value = get_md5(word_file)
    temp_file = TEMP_PATH / f"{file_md5_value}.html"
    attach_file_dir = temp_file.parent / f"{file_md5_value}.files"
    attach_file_map = {}

    with OpenWordFile(word_file) as doc:
        doc.SaveAs(str(temp_file.absolute()), 10)  # txt=4, html=10, docx=16, pdf=17

    for item in Path(attach_file_dir).rglob('*'):
        attach_file_md5_name = get_md5(item) + item.suffix
        raw_path = f"{file_md5_value}.files/{item.name}"
        rep_path = STATIC_FILE_PREFIX + attach_file_md5_name
        attach_file_map[raw_path] = rep_path
        shutil.copy(str(item.absolute()), (TGT_STATIC_PATH / attach_file_md5_name).absolute())

    def _replace(reg):
        return attach_file_map[reg.group()]

    with temp_file.open(mode='rt', encoding='gbk') as f:
        content = f.read()
        if attach_file_map:
            content = re.sub(fr"{'|'.join(attach_file_map)}", _replace, content)
        process_file_data({
            'filename': word_file.name,
            'file_md5_value': file_md5_value,
            'content': content
        })

    # 处理之后可以删除此临时文件
    # temp_file.unlink(missing_ok=True)


def run():
    for dir_ins in map(Path, SRC_PATH_LIST):
        for file_ins in dir_ins.rglob('**/*.doc*'):
            parse(file_ins)


if __name__ == '__main__':
    run()
    word_app.Quit()
